import asyncio

from apscheduler.schedulers.blocking import BlockingScheduler

from app_v2.bili_api.api import ApiSession
from app_v2.bili_api.common import cookie_
from app_v2.db import db

scheduler = BlockingScheduler()


# TODO:
# every info will be preserved 7 days


@scheduler.scheduled_job('cron', minute='*/5')
def video_job():
    async def job(bvids):
        async with ApiSession(cookie_) as session:
            result = await asyncio.gather(
                *map(lambda bvid: session.video(bvid).info(), bvids)
            )
        for info in result:
            print(f"bvid {info.bvid} info Done")
            db.execute(
                "INSERT INTO video_info "
                "(bvid, view_count, danmaku_count, reply_count, like_count, coin_count, favorite_count, share_count) "
                "VALUES (%s, %s, %s, %s, %s, %s, %s, %s)",
                [info.bvid,
                 info.view,
                 info.danmaku,
                 info.reply,
                 info.like,
                 info.coin,
                 info.favorite,
                 info.share]
            )

    try:
        res = db.fetch_all("SELECT DISTINCT bvid FROM user_likes_video")
        asyncio.run(job(map(lambda item: item["bvid"], res)))
    except Exception as e:
        print(e)


@scheduler.scheduled_job('cron', minute='*/5')
def user_job():
    async def job(mids):
        async with ApiSession(cookie_) as session:
            result = await asyncio.gather(
                *map(lambda mid: session.up(mid).info(), mids)
            )
        for info in result:
            print(f"mid {info.mid} info Done")
            db.execute(
                "INSERT INTO user_info "
                "(mid, follower, like_count, video_count, following, view_count)"
                "VALUES (%s, %s, %s, %s, %s, %s)",
                [info.mid,
                 info.followers,
                 info.likes,
                 info.videos,
                 info.following,
                 info.views]
            )

    try:
        res = db.fetch_all("SELECT DISTINCT mid FROM user_likes_up")
        asyncio.run(job(map(lambda item: item["mid"], res)))
    except Exception as e:
        print(e)


def check_cookies():
    try:
        data = db.fetch_all("SELECT uid, cookies FROM bwdap_users")

        async def job(items):
            async def sub_job(item):
                async with ApiSession.default() as session:
                    return item["uid"], await session.check_cookie(item["cookies"])

            return await asyncio.gather(*map(lambda item: sub_job(item), items))

        return asyncio.run(job(data))
    except Exception as e:
        print(e)


if __name__ == '__main__':
    # result = check_cookies()
    # handle the outdated cookies
    # cookies = list(map(lambda item: item[1], result))
    scheduler.start()
